#include "CameraManipulator.h"

CameraManipulator::CameraManipulator():
m_State(None)
{
}

void CameraManipulator::home(const osgGA::GUIEventAdapter &, osgGA::GUIActionAdapter &)
{
	m_Matrix = osg::Matrix::inverse( osg::Matrix::lookAt(_homeEye, _homeCenter, _homeUp) );
}

bool CameraManipulator::handle(const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa)
{
	if(ea.getEventType() == osgGA::GUIEventAdapter::KEYDOWN && ea.getKey() == ' ')
	{
		home(ea, aa);
	}
	else if(ea.getEventType() == osgGA::GUIEventAdapter::PUSH)
	{
		switch(ea.getButton())
		{
		case osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON:
			m_LastMousePosition.set(ea.getX(), ea.getY());
			m_LastPosition = m_Matrix.getTrans();
			m_State = Dragging;
			return true;
			break;
		}
	}
	else if(ea.getEventType() == osgGA::GUIEventAdapter::RELEASE)
	{
		m_State = None;
		return true;
	}
	else if(ea.getEventType() == osgGA::GUIEventAdapter::DRAG && ea.getButtonMask() & osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON)
	{
		osg::Vec2 m(ea.getX(), ea.getY());
		osg::Vec2 delta = (m_LastMousePosition - m) * 0.1f;
		m_Matrix.setTrans( m_LastPosition + osg::Vec3(delta.x(), delta.y(), 0.f) );
		return true;
	}

	return false;
}